<?php
/*
 * inc-addQuestion.php
 * Retral/CSCD494 Winter 2009
 * Eastern Washington University
 *
 * File Description:
 * 
 * This file is used to add questions into the database. Error checking is done
 * to make sure the user enters a title and uploads the required files. If the
 * required files are not specified the question is marked as incomplete but
 * still submitted.
 *
 * Other:
 *
 */


/* 
 * Set up $page_name
 * This name will be compared to PAGE_NAME in NAV_URLS table (stored in session) and verify permission for given user.
 */
$page_name = "Add Question";
$page_name = strtoupper($page_name);

require('KinID.php');

// Is user logged in, and has permissions?
//if (isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] !="" && $_SESSION['pagePermissions'][$page_name] == 1)
//{

if(isset($_POST['newVersion']))
	$newVersion=$_POST['newVersion'];
else
	$newVersion = -1;

        // initializing variables
        $submitted = false;
        $questionLoaded = false;
        $pointsNotValid = false;
        $titleNotValid = false;
        $inputNotValid = false;
        $firstName = 'Non Existing User';
        $lastName  = '';
        $author = -1;
        
        echo '<h2>';
        echo "<span class='header-text'>Add Question</span><br/>";

            
        // connection to be used to connect to the database
        // ORA_CON_UN, ORA_CON_PW, ORA_CON_DB are global variables
        $conn = oci_connect(ORA_CON_UN, ORA_CON_PW, ORA_CON_DB);
        
        
        $query = 'SELECT first_name, last_name ' .
                 ' FROM APE_USER' .
                 ' WHERE user_id = :userId ';
        $stmt = oci_parse($conn, $query);
        oci_bind_by_name($stmt, ':userId', $_SESSION['userID']);
        oci_execute($stmt, OCI_DEFAULT);

        if($result = oci_fetch_assoc($stmt))
        {
            do
            {     
                foreach ($result as $name => $column)
                {
                    if(strtoupper($name) == 'FIRST_NAME')
                        $firstName = $column;
                    else if(strtoupper($name) == 'LAST_NAME')
                        $lastName = $column;
                }
            }while($result = oci_fetch_assoc($stmt));
        } 
            
        $author = $_SESSION['userID'];
            
        $query = 'SELECT * 
                  FROM QUESTION_TYPE
                  ORDER BY type_code ASC ';
        $stmt = oci_parse($conn, $query);
        oci_execute($stmt);
        
        $pointsArray = array();
        $namesArray  = array();
        if($result = oci_fetch_assoc($stmt))
        {
            do
            {     
                foreach ($result as $name => $column)
                {
                   if(strtoupper($name) == 'TYPE_CODE')
                       $x = $column;                        
                   else if(strtoupper($name) == 'TYPE_DESCRIPTION')
                       $namesArray[$x] = strtoupper($column) ;
                   else if(strtoupper($name) == 'POINTS')
                   {
                       $pointsArray[$x] = $column;
                       $x++;
                   }

                }
            }while($result = oci_fetch_assoc($stmt));
        }

        if (isset($_POST['submit'])) 
        {
            $submitted = true;
            $pointsNotValid = ($submitted && strlen($_POST['points']) == 0) || preg_match("/\D/", $_POST['points']) != 0;
            $titleNotValid = $submitted && strlen(trim($_POST['question_title'])) == 0;
            $inputNotValid = $submitted && (empty($_FILES["pInput"]["name"]) || empty($_FILES["pOutput"]["name"])
                             //|| empty($_FILES["tInput"]["name"]) || empty($_FILES["tOutput"]["name"]) 
                             || empty($_FILES["criteria"]["name"]) || empty($_FILES["problem"]["name"]));        
            
            if(!$titleNotValid && !$pointsNotValid && $_POST['points'] <= $pointsArray[$_POST['questionType']])
            {
                $query = 
                    "INSERT INTO question_content (question_content_id, question_title, author_id, points) ".
                    "VALUES (question_content_s1.nextval, :title, :author, :points)";
                    
                $stmt = oci_parse($conn, $query);
                
                oci_bind_by_name($stmt, ':title', $_POST['question_title']);
                oci_bind_by_name($stmt, ':author', $author);    
                oci_bind_by_name($stmt, ':points', $_POST['points']);
                
                if(oci_execute($stmt, OCI_DEFAULT))
                {            
                    oci_commit($conn);
                    oci_free_statement($stmt);
                    
                    if($newVersion == -1)
					{
						//get next question_s1(sequence#) and save it.
						//$query ="SELECT question_s1.nextval FROM DUAL; ";
						$query = "SELECT question_s1.nextval FROM DUAL";
						$stmt = oci_parse($conn, $query);						
						oci_execute($stmt, OCI_DEFAULT) or die("errorrrs");
						$row = oci_fetch_array ($stmt, OCI_BOTH);
						$qid = $row[0];
					
						$query = 
								" DECLARE " .
								"     question_id_temp NUMBER := 0; " .
								" BEGIN " .
								"                                                                  " .
								"     INSERT INTO question(question_id, q_version, question_type_code, question_content_id, date_modified, reviser_user_id, q_revision) " .
								"     VALUES (:qid, 0, :type, question_content_s1.currval, SYSDATE, :author, 0); " .
								"                                                                                    " .
								"     INSERT INTO change_request (question_id, q_version, request_code, comments) " .
								"     VALUES (:qid, 0, :code, :comments); " .
								" END; "; 
							$stmt = oci_parse($conn, $query);	
							oci_bind_by_name($stmt, ':qid', $qid); 				
					}					
					else if($newVersion != -1)
					{
						$qid = $newVersion;
						$query = 
								" DECLARE " .
								"     question_ver_temp NUMBER := 0; " .
								" BEGIN " .
								"     SELECT MAX(q_version) INTO question_ver_temp FROM question where question_id = $newVersion GROUP BY question_id; " .
								"                                                                  " .
								"     INSERT INTO question(question_id, q_version, question_type_code, question_content_id, date_modified, reviser_user_id, q_revision) " .
								"     VALUES ($newVersion, (question_ver_temp+1), :type, question_content_s1.currval, SYSDATE, :author, 0); " .
								"                                                                                    " .
								"     INSERT INTO change_request (question_id, q_version, request_code, comments) " .
								"     VALUES ($newVersion, (question_ver_temp+1), :code, :comments); " .
								" END; ";
						$stmt = oci_parse($conn, $query);		
					}	
                   
                    
                    $requestCode = 2; // New question
                    //$comments = 'New Question';
                    $comments = ' ';
                    if($inputNotValid)
                    {
                        $requestCode = 6; // incomplete information
                        //$comments = 'Incomplete Information';
                    }    
                    oci_bind_by_name($stmt, ':type', $_POST['questionType']); 
                    oci_bind_by_name($stmt, ':code', $requestCode); 
                    oci_bind_by_name($stmt, ':comments', $comments); 
                    oci_bind_by_name($stmt, ':author', $author); 
                    
                    if(oci_execute($stmt, OCI_DEFAULT))
                    { 
                        oci_commit($conn);
                        oci_free_statement($stmt);
                        
						/*
							This section uploads the file source(.txt) and correctly identifies them based upon the kinID
						*/
                        $kin = 0;
						$counter = 0;
                        $kinArray = array(provided_input(), provided_output(), test_input(), test_output(),  scoring(), instr());
                        $files = array("pInput", "pOutput", "tInput", "tOutput", "criteria", "problem");      
						//this relies on that user has the same number of input files as output files
						$providedInputPairCount = count($_FILES["pInput"]["name"]);						
						$providedOutputPairCount = count($_FILES["pOutput"]["name"]);
						$graderInputPairCount = count($_FILES["tInput"]["name"]);
						$graderOutputPairCount = count($_FILES["tOutput"]["name"]);
						
                        for($x = 0; $x < sizeof($files); $x++) //goes through each file type(student input, student output, etc..)
                        {
							$counter=0;
							for($z = 0; $z<4; $z++)//goes through each file of that type  4 = MAX uploads
							{
								if(!empty($_FILES[$files[$x]]["name"][$z])) 
								{
									$kin = $kinArray[$x];
									$counter++;
									 $query = 
											"INSERT INTO source_file (source_file_id, question_id, q_version, kin, source_file_name, source_file, io_pair) ".
											"VALUES (source_file_s1.nextval, question_s1.currval, 0, :kin, :file_name, EMPTY_BLOB(), :io_pair ) ". 
											"RETURNING source_file INTO :sourceFile "; 
										
									if($newVersion != -1)
											$query = 
											" DECLARE " .
											"question_ver_temp NUMBER := 0; " .
											"BEGIN ".
											"SELECT MAX(q_version) INTO question_ver_temp from question where question_id =$newVersion group by question_id; ".
											"INSERT INTO source_file (source_file_id, question_id, q_version, kin, source_file_name, source_file, io_pair) ".
											"VALUES (source_file_s1.nextval, $newVersion, question_ver_temp, :kin, :file_name, EMPTY_BLOB(), :io_pair) ". 
											"RETURNING source_file INTO :sourceFile; ".
											"END; ";
	
									// Insert the BLOB from PHP's tempory upload area    
									$lob_file = oci_new_descriptor($conn, OCI_D_LOB);  
									$stmt = oci_parse($conn, $query);
									oci_bind_by_name($stmt, ':file_name', $_FILES[$files[$x]]['name'][$z])or die("error binding1");
									oci_bind_by_name($stmt, ':kin', $kin)or die("error binding2");
									oci_bind_by_name($stmt, ':sourceFile', $lob_file, -1, OCI_B_BLOB)or die("error binding3");
									oci_bind_by_name($stmt, ':io_pair', $counter)or die("counter");
									
									if(!oci_execute($stmt, OCI_DEFAULT))
									{
										$e = oci_error($stmt);
										
										echo "ERROR: ".$e['message'];
										die();
									}
									
									if($lob_file->savefile($_FILES[$files[$x]]['tmp_name'][$z]))
									{
										oci_commit($conn);
										oci_free_statement($stmt);
										
									}
									else
										echo "<script type=\"text/javascript\"> alert(\"ERROR!A.\"); </script>";
								}								
								
								
								
							}	
                        }                                           
                        echo "<span class='header-text'> <font color='#00FF00'> Question Successfully Uploaded! </font></span><br/>";                
                        
                        $numberOfSourceFiles = 1;
                        if($_POST['numberOfSourceFiles'] > 0)
                            $numberOfSourceFiles = $_POST['numberOfSourceFiles'];
                        for($x = 1; $x <= $numberOfSourceFiles; $x++)
                        {
                            $fileName = "source".$x;
                            $checked = false;
                            $kin = source_file();
                            if(!isset($_POST['check' . $x]))
                                $kin = class_file(); // Non Java File added as source
                            
                            if(!empty($_FILES[$fileName]["name"]))
                            {
                                $query = 
                                    "INSERT INTO source_file (source_file_id, question_id, q_version, kin, source_file_name, source_file) ".
                                    "VALUES (source_file_s1.nextval, question_s1.currval, 0, :kin, :file_name, EMPTY_BLOB()) ". 
                                    "RETURNING source_file INTO :sourceFile ";
								
								if($newVersion != -1)
											$query = 
											" DECLARE " .
											"question_ver_temp NUMBER := 0; " .
											"BEGIN ".
											"SELECT MAX(q_version) INTO question_ver_temp from question where question_id =$newVersion group by question_id; ".
											"INSERT INTO source_file (source_file_id, question_id, q_version, kin, source_file_name, source_file) ".
											"VALUES (source_file_s1.nextval, $newVersion, question_ver_temp, :kin, :file_name, EMPTY_BLOB()) ". 
											"RETURNING source_file INTO :sourceFile; ".
											"END; ";
                                    
                                    $lob_source_file = oci_new_descriptor($conn, OCI_D_LOB);   

                                    $stmt = oci_parse($conn, $query);
                                    oci_bind_by_name($stmt, ':file_name', $_FILES[$fileName]['name']);
                                    oci_bind_by_name($stmt, ':kin', $kin);
                                    oci_bind_by_name($stmt, ':sourceFile', $lob_source_file, -1, OCI_B_BLOB);
                                    oci_execute($stmt, OCI_DEFAULT);
                                    
                                    if($lob_source_file->savefile($_FILES[$fileName]['tmp_name']))
                                    {
                                        oci_commit($conn);
                                        oci_free_statement($stmt);
                                    }
                                    else
                                        echo "<script type=\"text/javascript\"> alert(\"ERROR!B.\"); </script>"; 
                            }
                        }
                        $questionLoaded = true;
                        oci_commit($conn);
						
						
						//if file upload was successful - redirect user input/output validation
						$query = "SELECT MAX(q_version) from question where question_id = :qid";
						$stmt = oci_parse($conn, $query);
						oci_bind_by_name($stmt, ':qid', $qid); 						
						oci_execute($stmt, OCI_DEFAULT) or die("errorrrs_qver");
						$row = oci_fetch_array ($stmt, OCI_BOTH);
						$qver = $row[0];
						
						
						//$providedInputPairCount;						
						//$providedOutputPairCount;
						//$graderInputPairCount ;
						//$graderOutputPairCount;

					//echo "<meta http-equiv='refresh' content='0;url=http://cscd494-l.cslabs.ewu.edu:7878/apegen?id=$qid&qver=$qver&providedInputPairCount=$providedInputPairCount&providedOutputPairCount=$providedOutputPairCount&graderInputPairCount=$graderInputPairCount&graderOutputPairCount=$graderOutputPairCount'>";
                    //http://cscd494-l.cslabs.ewu.edu:7878/apegen?runCode=test&id=161&qver=0&providedInputPairCount=1&providedOutputPairCount=1
					echo "<meta http-equiv='refresh' content='0;url=http://cscd494-l.cslabs.ewu.edu:7878/apegen?runCode=test&id=$qid&qver=$qver&providedInputPairCount=$providedInputPairCount&providedOutputPairCount=$graderInputPairCount'>";

					
					}
                    else
                    {
                        echo "<span class='header-text'> <font color='#FF0000'> Question Submission Failed! Contact the Administrator. </font></span><br/>";
						$e = oci_error($stmt);
						echo $e['message'];
                        $questionLoaded = true;                
                    }
                }
                else 
                {
                    echo "<span class='header-text'> <font color='#FF0000'> Question Submission Failed! </font></span><br/>";
                    $questionLoaded = true;
                }        

                oci_free_statement($stmt);
                oci_close($conn); 
            }
            else
                echo "<span class='header-text'> <font color='#FF0000'> Question Submission Failed! </font></span><br/>";
        }    
        echo '</h2>';
        

		?>

			<link rel="stylesheet" href="css/preview.css" type="text/css" media="screen">
			<!--<script type="text/javascript" language="javascript" src="script/addQuestion.js"></script> -->
			<script src="script/jquery.js" type="text/javascript" language="javascript"></script>
			<script src="script/jquery.MultiFile.js" type="text/javascript" language="javascript"></script>	
			<body onLoad="document.getElementById('<? if(isset($_POST['submit']) && $pointsNotValid && !$titleNotValid) echo 'points'; else echo 'question_title'; ?>').focus()">
			<form action="<?php echo $_SERVER['PHP_SELF'];  ?>?page=addQuestion&good=true" method="POST" enctype="multipart/form-data" >
			
				<p  class='required'>Author: <? echo $firstName; if($lastName != '') echo ', ' . $lastName; ?><br>
					Created: <?PHP echo date("m/d/Y"); ?>
				</p>
				
				<p><strong> <br>REQUIRED </strong></p>
				<p>
					<?
						if($titleNotValid)
						{    
							echo '<font color="#FF0000">Title: &nbsp</font>'; 
						} 
						else 
							echo 'Title: &nbsp';
					
					?>
					<input type='text' name='question_title' id='question_title' maxlength=40 class='required' value='<?=$_REQUEST['question_title']?>'> 
				
				
					<?
						if($titleNotValid)    
							echo '<br><font color="#FF0000">*Title can not be blank.</font>'; 
					?>
				</p>

				<p> Question Type:
					<select name="questionType" id="questionType" onChange="changePoints(this.form, this)">
					<?
						$max = 30;
						foreach($pointsArray as $index => $value)
						{
							echo '<option value =' . $index;
							if(isset($_POST['submit']) && $_POST['questionType'] == $index)
							{   echo " selected='yes'"; $max = $value; } 
							echo  '>' . strtoupper($namesArray[$index]);
							echo ' - ' . $value. ' points</option>';
						}   
					?>
					</select>
				</p>
				<p>
					<? 
						if($pointsNotValid)
						{    
							echo '<font color="#FF0000">Points Possible:</font>'; 
						} 
						else 
							echo 'Points Possible:';
					
						echo '<select name="points" id="points">';
					
						for($x = 5; $x <= $max; $x = $x + 5)
						{
							echo '<option value =' . $x;
							if(isset($_POST['submit']) && $_POST['points'] == $x)
								echo " selected='yes'"; 
							 echo  '>' . $x . '</option>';
						}   
					
						echo '</select>';
				   
						if($pointsNotValid)
							echo '<br><font color="#FF0000"> *Please make sure points are not blank and contain only digits without spaces. </font><br><br>';
						if($_POST['points'] > $pointsArray[$_POST['questionType']])
							echo '<br><font color="#FF0000"> *The question type you selected requires a maximum of ' . $pointsArray[$_POST['questionType']] . ' points. </font><br><br>';
					?>
				</p>
				<table>
					<tr>     Provided to Student: </tr>
					<tr><td> Input: </td> <td> <input type='file' name='pInput[]' id='pInput' class='required multi' value=''> </td></tr>
				<tr><td> Ouptut: </td> <td> <input type='file' name='pOutput[]' id='pOutput' class='required multi' value=''> </td></tr>
				</table> <br />
				<table>
					<tr>     Grading: </tr>
					<tr><td> Input:     </td> <td> <input type='file' name='tInput[]' class='required multi' value=''>   </td></tr>
					<tr><td> Ouptut:    </td> <td> <input type='file' name='tOutput[]' class='required multi' value=''>  </td></tr>
					<tr><td> Criteria:  </td> <td> <input type='file' name='criteria[]'  value=''> </td></tr>
				</table>
				<p>Problem Instructions:
					<br><input type='file' name='problem[]' class='required' value=''>
				</p>
				<p><strong> <br>OPTIONAL </strong></p>
				
					<table>
					<tr><td> Question Source/Class Files: </td></tr>
					<tr>
						<td><input type='file' name='source1' class='required' value=''> </td>
						<td><input type='checkbox' name='check1' class='required' value='' <? if(!isset($_POST['submit']) || isset($_POST['check1'])) echo "checked"; ?> > Provide As Source <br> </td>
					</tr>
					<?
						for($x = 2; $x <= $_POST['numberOfSourceFiles']; $x++)
						{   
							echo "<tr><td><input type='file' name='source" . $x . "' class='required' value=''> </td>";
							if(!isset($_POST['submit']))
								echo "<td><input type='checkbox' name='check" . $x . "' class='required' value='' checked> Provide As Source<br> </td></tr>";
							else
							{
								echo "<td><input type='checkbox' name='check" . $x . "' class='required' value='' ";
								if(isset($_POST['check' . $x])) 
									echo 'checked'; 
								echo " > Provide As Source <br> </td></tr>";
							}
						}   
						
						if($_POST['numberOfSourceFiles'] >= 1)
							echo "<input type='hidden' name='numberOfSourceFiles'  value='" . $_POST['numberOfSourceFiles'] . "'/>";
						if($newVersion != -1)
							echo "<input type='hidden' name='newVersion' value='$newVersion' />"
					?>
					</table>
					
			   
				<p><input class='button' type='submit' value='Upload' name='submit' id='submit'></p>
		  

			</form>
			</body>
<?php
/*}
else
{
	echo "Invalid credentials";
	echo "<META http-equiv=\"refresh\" content=\"0;URL=index.php?page=login&ld=0\">";
}	*/
?>
